﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ContentPage : System.Web.UI.Page
{
    private string queryType; //query for content type
    private string queryCategory; //query for subject category

    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (!User.IsInRole("websiteUser"))
        {
            Response.Redirect("RegisterControl.aspx"); //if user is not logged in, redirect to register screen
        }

        queryType = ((ContentMaster)this.Master).x; //get type query from variable in masterpage
        queryCategory = ((ContentMaster)this.Master).y; //get category query from variable in masterpage
        string strConnString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; //connection string to database
        SqlConnection Connection = new SqlConnection(strConnString); //set sqlconnection to connection string
        Session["ConnDB"] = Connection;
        connectDB(); //method for sql connection/command
    }

    protected void Page_Load(object sender, EventArgs e)
    {
//       EduLogger.logActivity(User.Identity.Name, "enter content", HttpContext.Current.Request.Url.AbsoluteUri);
    }

    public void connectDB()
    {
        SqlConnection Connection = (SqlConnection)Session["ConnDB"];
        string SqlQuery; //sql query for database
        if (queryCategory == null || queryType == null) //if the type query equals all or is not included in adress 
        {
            SqlQuery = "SELECT * FROM videoTable"; //show all content from database on contentpage
        }
        if(queryCategory != null && queryType.Equals("all")) { 
            SqlQuery = "SELECT * FROM videoTable WHERE category='" + queryCategory + "';"; //select all content items and their category
        }
        else //if the query does exist, do this
        {
            SqlQuery = "SELECT * FROM videoTable WHERE filetype ='" + queryType + "'" + "AND category='" + queryCategory + "';"; //select content items according to type and their category
        }

        SqlCommand cmd = new SqlCommand(SqlQuery, Connection); //new command for database
        Connection.Open(); //open connection to database
        SqlDataReader Reader = cmd.ExecuteReader(); //execute command
        Repeater1.DataSource = Reader; //set the repeater to Reader
        Repeater1.DataBind(); //bind data to the repeater
        Connection.Close(); //close connection
    }

}